# 项目名：小说爬取
# 作者：张见葛
# 该文件主要是一些打印相关的方法

from rich.theme import Theme
from rich.console import Console
from rich.table import Table
from rich import print
from rich.panel import Panel
import random,time
from rich.progress import BarColumn,TimeRemainingColumn,Progress
import sys

# 日志输出对象
custom_theme = Theme({
    "info": "dim cyan",
    "warning": "magenta",
    "danger": "bold red"
})
console = Console(theme=custom_theme)


def get(obj, label):
    labels = label.split('/')
    o = obj
    for la in labels:
        o = o.get(la)
    return o

# 打印欢迎使用的标语
def print_welcome_info():
    print(Panel('''
    ###############欢迎使用小说爬虫来免费下载您喜爱的内容################
        该项目目前还处于开发过程中，暂时只支持如下站点的内容，后续将支持增加站点支持！
            -> 笔趣阁【https://www.bqg9527.com】
    ''', title='小说爬虫', style="bold blue", width=100))


# 开始打印搜索结果
def print_search_result(novels):
    print('\n\n\n\n>>>>>>>>>>>>>>搜索结果如下：')
    table = Table(show_header=True, header_style="bold red")
    table.add_column("序号", style="dim", justify="center")
    table.add_column("小说名称", justify="center")
    table.add_column("作者", justify="center")
    table.add_column("来源", justify="center")
    table.add_column("详情页地址", justify="center")
    for inx, novel in enumerate(novels):
        table.add_row(str(inx+1), get(novel, 'novel_name'), get(novel, 'author'), get(novel, 'source_name'), get(novel, 'url'))
    console.print(table)
    while True:
        try:
            # 获取用户想要下载的小说序号
            want_index = input("请输入想要下载的小说序号【输入exit可退出】: ")
            if 'exit'.__eq__(want_index):
                progress = Progress("[progress.description]{task.description}",
                                    BarColumn(),
                                    "[progress.percentage]{task.percentage:>3.0f}%",
                                    TimeRemainingColumn(),
                                    "{task.completed}/{task.total}")
                with progress:
                    task_id = progress.add_task("[red]退出中...", total=100)
                    while True:
                        dealing_part = random.randint(0, 10)
                        dealt_part = progress.tasks[task_id].completed
                        if dealt_part + dealing_part >= 100:
                            progress.update(task_id, advance=100 - dealt_part)
                            break
                        progress.update(task_id, advance=dealing_part)
                        time.sleep(0.2)
                sys.exit(0)
            elif 0 < int(want_index) <= len(novels):
                return int(want_index)
            else:
                print(">> 输入的序号不在查询范围内,请重新输入！")
        except Exception:
            print("输入有误，请重新输入")


# 打印爬取的章节内容
def print_chapter_list(chapters):
    print('\n\n\n\n>>>>>>>>>>>>>>搜索结果如下：')
    table = Table(show_header=True, header_style="bold red")
    table.add_column("序号", style="dim", justify="center")
    table.add_column("章节名称", justify="center")
    table.add_column("URL地址", justify="center")
    for inx, chapter in enumerate(chapters):
        table.add_row(str(inx+1), get(chapter, 'chapter_name'), get(chapter, 'url'))
    console.print(table)